package com.zhangfei;

public class AtomicityProblem {
    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        // 创建多个线程，每个线程都会增加计数器
        int numThreads = 1000;
        Thread[] threads = new Thread[numThreads];
        for (int i = 0; i < numThreads; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    count++; // 这不是原子操作
                }
            });
        }

        // 启动所有线程
        for (Thread thread : threads) {
            thread.start();
        }

        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }

        // 打印最终的计数值，它应该等于 numThreads * 1000，但由于原子性问题，它可能小于这个值
        System.out.println("Final count: " + count);
        System.out.println("Expected count: " + numThreads * 1000);
    }
}
